package cn.alone.basic.controller;

import cn.alone.basic.util.AjaxResult;
import cn.alone.basic.util.FastDfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 文件上传接口
 */
@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {

    //1.上传文件的接口
    @PostMapping
    public AjaxResult upload(@RequestPart(required = true, value = "file") MultipartFile file){
        try {
            String filename = file.getOriginalFilename();//  105.jpg
            String extName = filename.substring(filename.lastIndexOf(".") + 1);//jpg
            String uploadPath = FastDfsUtil.upload(file.getBytes(), extName);

            return AjaxResult.me().setResultObj(uploadPath);//把上传之后的相对路径设置给resultObj属性
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("上传失败!!!");
        }
    }

    //2.删除文件的接口
    @DeleteMapping  // ?path=/group1/M00/02/22/rBE3kWHNVcKAf1QKAAF-6xZ0lWg132.jpg
    public AjaxResult delete(@RequestParam String path){
        try {
            String pathTmp = path.substring(1); // group1/M00/02/22/rBE3kWHNVcKAf1QKAAF-6xZ0lWg132.jpg
            String groupName =  pathTmp.substring(0, pathTmp.indexOf("/")); //goup1
            String fileName = pathTmp.substring(pathTmp.indexOf("/")+1);// M00/02/22/rBE3kWHNVcKAf1QKAAF-6xZ0lWg132.jpg
            FastDfsUtil.delete(groupName, fileName);

            return AjaxResult.me();//把上传之后的相对路径设置给resultObj属性
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("删除失败!!!");
        }
    }

}
